import { defineStore } from "pinia";
import { type RouteLocationNormalizedLoaded } from "vue-router"
import { ClassTag } from '#/index'
import router from '@/router/index'

export const useStoreTags = defineStore('Tags', {
    persist: true,
    state: () => ({
        tagList: [new ClassTag("/index/dashboard", "dashboard", 'dashboard')]
    }),
    actions: {
        // 添加标签
        pushTag(route: RouteLocationNormalizedLoaded, index: number = -1) {
            const { fullPath, meta, name } = route
            //过滤重定向页面 
            if ("redirect" === name) {
                return
            }
            let openTags = this.tagList
            let findTag = openTags.find((p: ClassTag) => p.fullPath == fullPath)
            if (!findTag) {
                var i = index > -1 ? index : openTags.length
                openTags.splice(i, 0, new ClassTag(fullPath, meta.title as string, name as string))
            }
        },
        // 删除标签 
        removeTab(index: number) {
            let openTag = this.tagList
            let tag = openTag[index]
            let route = router.currentRoute.value//当前路由
            if (route.fullPath == tag.fullPath) {
                let { fullPath } = openTag[index + 1] || openTag[index - 1]
                router.push(fullPath)
            }
            openTag.splice(index, 1)
        },
        // 点击标签页
        handleTabs(index: number) {
            let tag = this.tagList[index]
            console.log(tag.fullPath, 'tag');
            let route = router.currentRoute.value
            if (tag.fullPath != route.fullPath) {
                router.push(tag.fullPath)
            }
        },
        // 点击关闭右侧标签
        removeRightTab(fullPath: string) {
            let route = router.currentRoute.value
            let index = this.tagList.findIndex(i => i.fullPath == fullPath)//右击标签页
            let activeIndex = this.tagList.findIndex(i => i.fullPath == route.fullPath)//当前显示标签页
            // 删除右侧所有标签页
            this.tagList.splice(index + 1)
            //当当前标签页的位置在点击的标签页左边时，
            if (activeIndex > index) {
                router.push(this.tagList[index].fullPath)
            }
        },
        // 移除全部标签页
        removeAllTab() {
            this.tagList.splice(1)
            router.push("/")
        },
        // 移除当前标签页
        removeNowTags() {
            let route = router.currentRoute.value//当前路由
            let index = this.tagList.findIndex(i => i.fullPath == route.fullPath)//右击标签页
            this.tagList.splice(index, 1)
        }
    }
})
